package com.imax.center.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imax.center.cache.RedisService;
import com.imax.center.constant.H3yunApiConstants;
import com.imax.center.constant.RedisConstants;
import com.imax.center.domain.AlarmConfig;
import com.imax.center.service.DataCacheService;
import com.imax.center.service.impl.h3yun.H3yunOperate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 数据缓存服务实现类
 */
@Slf4j
@Service
public class DataCacheServiceImpl implements DataCacheService {

    @Autowired
    private RedisService redisService;

    @Autowired
    H3yunOperate h3yunOperate;

    @Override
    public JSONArray getRegionData() {
        // 从Redis缓存中获取token
        String regionDataStr = (String) redisService.get(RedisConstants.REGION_AREA_KEY);
        
        if (regionDataStr == null) {
            synchronized (this) {
                // 双重检查，防止并发问题
                regionDataStr = (String) redisService.get(RedisConstants.REGION_AREA_KEY);
                if (regionDataStr == null) {
                    return this.refreshRegionData();
                }
            }
        }
        
        return JSON.parseArray(regionDataStr);
    }

    @Override
    public JSONArray refreshRegionData() {
        Map<String, Object> queryParams = new HashMap<>();
        String ReturnItems = "AreaCode, AreaName, ParentCode, CityLevel, Lng, Lat";
        JSONArray regionData = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_REGION_AREA, queryParams, ReturnItems, true, 2);
        String regionDataStr = JSON.toJSONString(regionData);
        redisService.set(RedisConstants.REGION_AREA_KEY, regionDataStr,
                RedisConstants.REGION_AREA_EXPIRE, TimeUnit.DAYS);
        log.info("成功缓存行政区划数据，数据条数: {}，将在{}秒后过期",
                regionData.size(), RedisConstants.REGION_AREA_EXPIRE);
        return regionData;
    }

    @Override
    public JSONArray getSensorDevice() {
        // 从Redis缓存中获取传感器设备数据
        String sensorDeviceStr = (String) redisService.get(RedisConstants.SENSOR_DEVICE_KEY);
        
        if (sensorDeviceStr == null) {
            synchronized (this) {
                // 双重检查，防止并发问题
                sensorDeviceStr = (String) redisService.get(RedisConstants.SENSOR_DEVICE_KEY);
                if (sensorDeviceStr == null) {
                    return this.refreshSensorDevice();
                }
            }
        }
        
        return JSON.parseArray(sensorDeviceStr);
    }

    @Override
    public JSONArray refreshSensorDevice() {
        Map<String, Object> queryParams = new HashMap<>();
        // 查询全部字段
        String ReturnItems = "*";
        JSONArray sensorDeviceData = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_SENSOR_DEVICE, queryParams, ReturnItems, true, 2);
        String sensorDeviceStr = JSON.toJSONString(sensorDeviceData);
        redisService.set(RedisConstants.SENSOR_DEVICE_KEY, sensorDeviceStr,
                RedisConstants.SENSOR_DEVICE_EXPIRE, TimeUnit.DAYS);
        log.info("成功缓存传感器设备数据，数据条数: {}，将在{}天后过期",
                sensorDeviceData.size(), RedisConstants.SENSOR_DEVICE_EXPIRE);
        return sensorDeviceData;
    }

    @Override
    public List<AlarmConfig> getAlarmConfigList() {
        // 从Redis缓存中获取报警配置数据
        String cacheValueStr = (String) redisService.get(RedisConstants.ALARM_CONFIG_CACHE_KEY);
        
        if (cacheValueStr == null) {
            synchronized (this) {
                // 双重检查，防止并发问题
                cacheValueStr = (String) redisService.get(RedisConstants.ALARM_CONFIG_CACHE_KEY);
                if (cacheValueStr == null) {
                    return this.refreshAlarmConfig();
                }
            }
        }

        //使用JSON将字符串转换为List<AlarmConfig>
        return JSON.parseArray(cacheValueStr, AlarmConfig.class);
    }

    /**
     * 从H3yun加载站点预警配置并缓存到Redis
     * @return 站点配置列表
     */
    @Override
    public List<AlarmConfig> refreshAlarmConfig() {
        try {
            Map<String, Object> queryParams = new HashMap<>();
            JSONArray result = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_ALARM_CHECK_ITEM, queryParams);
            if (result == null || result.isEmpty()) {
                return new ArrayList<>();
            }

            List<AlarmConfig> configList = new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {
                JSONObject item = result.getJSONObject(i);
                AlarmConfig config = new AlarmConfig();
                config.setCheckName(item.getString("CheckName"));
                config.setOrgId(item.getString("OrgId"));
                config.setOperate(item.getString("Operate"));
                config.setMaxField(item.getString("MaxField"));
                config.setMinField(item.getString("MinField"));
                config.setMaxWarnValue(item.getDouble("MaxWarnValue"));
                config.setMinWarnValue(item.getDouble("MinWarnValue"));
                config.setMaxAlarmValue(item.getDouble("MaxAlarmValue"));
                config.setMinAlarmValue(item.getDouble("MinAlarmValue"));
                configList.add(config);
            }

            // 存入Redis缓存
            if (!configList.isEmpty()) {
                String configListStr = JSON.toJSONString(configList);
                redisService.set(RedisConstants.ALARM_CONFIG_CACHE_KEY, configListStr, 
                        RedisConstants.ALARM_CONFIG_CACHE_EXPIRE, TimeUnit.DAYS);
                log.info("成功缓存报警配置数据，数据条数: {}，将在{}秒后过期",
                        configList.size(), RedisConstants.ALARM_CONFIG_CACHE_EXPIRE);
            }

            return configList;
        } catch (Exception e) {
            log.error("加载站点配置异常", e);
            return new ArrayList<>();
        }
    }

} 